package com.spi.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig {

    @Bean(name = "JobServiceExecutor")
    public Executor asyncServiceExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //cpu核心数
        int coreNum=Runtime.getRuntime().availableProcessors();
        log.info("cpu核心数："+coreNum);
        //配置核心线程数
        executor.setCorePoolSize(coreNum*2);
        //配置最大线程数
        executor.setMaxPoolSize(coreNum*2);
        //配置队列大小，每批次300条数据，可以保证同时处理1000*300条数据同时处理，而不执行拒绝策略
        executor.setQueueCapacity(400);
        //配置线程池中的线程的名称前缀
        //executor.setThreadNamePrefix("测试线程");
        //允许核心线程超时销毁
        executor.setAllowCoreThreadTimeOut(true);
        //线程空闲多长时间销毁
        executor.setKeepAliveSeconds(60);
       /* executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);*/

        // CALLER_RUNS：拒绝策略，当线程池没有处理能力的时候，该策略会直接在 execute 方法的调用线程中运行被拒绝的任务；如果执行程序已关闭，则会丢弃该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}
